package com.company.project.resolver;

import com.alibaba.fastjson.JSON;
import com.company.project.configurer.WebMvcConfig;
import com.company.project.core.MsgCode;
import com.company.project.core.MsgMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MyExceptionResolver implements HandlerExceptionResolver {

	private final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);


	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception e) {
		MsgMap result = new MsgMap();
		String message = null;
		if (e instanceof NoHandlerFoundException) {
			result.putCode(MsgCode.NOT_FOUND);
			result.putMsg("接口 [" + request.getRequestURI() + "] 不存在");
		} else if (e instanceof ServletException) {
			result.putCode(MsgCode.ERROR);
			result.putMsg(e.getMessage());
		} else {
			result.putCode(MsgCode.ERROR);
			result.putMsg("接口 [" + request.getRequestURI() + "] 内部错误，请联系管理员");
			if (handler instanceof HandlerMethod) {
				HandlerMethod handlerMethod = (HandlerMethod) handler;
				message = String.format("接口 [%s] 出现异常，方法：%s.%s，异常摘要：%s",
						request.getRequestURI(),
						handlerMethod.getBean().getClass().getName(),
						handlerMethod.getMethod().getName(),
						e.getMessage());
			} else {
				message = e.getMessage();
			}

		}
		if(message == null) message = JSON.toJSONString(result);
		logger.error(message, e);
		ModelAndView mv = new ModelAndView("error");
		return mv;
	}

}
